<script lang="ts" setup name="Menus">
import { onMounted, ref, reactive } from 'vue';
import { fetchMenusTreeApi, createMenuApi, updateMenusApi, deleteMenuByIdApi } from '@/api/system/menus/index'
import { FormInstance } from 'element-plus'
import { Icon } from '@iconify/vue'
import type { Menu, MenuTree } from '@/api/system/menus/type'
import { useI18n } from 'vue-i18n';
import { useDictStore } from '@/store';

const { t } = useI18n()
const dictStore = useDictStore()

const multipleSelection = ref<(string | number)[]>([])
const handleSelectionChange = (menus: Menu[]) => {
    multipleSelection.value = menus.map(menu => menu.id)
}
const tableData = ref<Menu[]>([])
const menusTree = ref<MenuTree[]>([])

const queryForm = reactive({
    name: '',
})

const fetchMenusTree = async () => {
    const res = await fetchMenusTreeApi(queryForm)
    tableData.value = res.data.data
    menusTree.value = [{ id: 0, name: '顶级菜单', children: res.data.data }]
    console.log(menusTree.value)
}

const queryFormRef = ref<FormInstance>()


// 抽屉
// 抽屉控制
const drawer = reactive({
    visible: false,
    mode: '',
})
// 
const drawerFormRef = ref<FormInstance>()

const defaultMenu =
{
    id: 0,
    name: '',
    locale: '',
    icon: '',
    parentId: 0,
    type: '',
    routePath: '',
    componentPath: '',
    sort: '0',
    authority: '',
    enabled: false,
    hidden: false,
    cached: false,
    link: false,
    children: [],
    createBy: '',
    createTime: '',
    updateBy: '',
    updateTime: ''
}
const menu = ref<Menu>(defaultMenu)
// 添加按钮点击事件
const addClick = (rowData: any) => {
    drawer.visible = true
    drawer.mode = 'add',
        menu.value.parentId = rowData.id
}
// 编辑按钮点击事件
const editClick = (rowData: any) => {
    drawer.visible = true
    drawer.mode = 'update'
    menu.value = { ...rowData }
    menu.value.parentId = rowData.parentId
}
// 添加/编辑页面关闭之前处理
const handleClose = (done: () => void) => {
    resetForm()
    done()
}
// 添加/编辑事件提交
const submit = async () => {
    try {
        const { children, ...data } = menu.value
        if (drawer.mode == 'add') {
            await createMenuApi(data)
        } else if (drawer.mode == 'update') {
            await updateMenusApi(data)
        }
        drawer.visible = false
        fetchMenusTree()
        ElMessage({
            message: '提交成功',
            type: 'success',
            plain: true,
        })
    } catch (err) {
        ElMessage({
            message: '提交失败',
            type: 'error',
            plain: true,
        })
    }
}
// 表单重置
const resetForm = () => {
    menu.value = defaultMenu
}
// 删除单个菜单
const deleteClick = async (id: string) => {
    try {
        await deleteMenuByIdApi(id)
        fetchMenusTree()
        ElMessage.success('提交成功')
    } catch (err) {
        ElMessage.error('删除失败')
    }
}

onMounted(() => {
    fetchMenusTree()
    dictStore.getDict(['status','menu_type'])
})
</script>

<template>
    <div h-full flex flex-col gap-row-4 box-border w-full>
        <div style="box-shadow: var(--el-box-shadow);" w-full box-border>
            <el-form :inline="true" :model="queryForm" style="margin: 1rem 1rem 0 1rem" ref="queryFormRef">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="queryForm.name" placeholder="请输入标题" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button @click="fetchMenusTree">查询</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div flex-1 overflow-hidden box-border position-relative pt-2 style="box-shadow: var(--el-box-shadow);">
            <div flex flex-col overflow-hidden box-border position-absolute w-full h-full>
                <div flex flex-justify-end p-4>
                    <ElButton circle @click="drawer.visible = true; drawer.mode = 'add'"><i i-ep-plus /></ElButton>
                    <ElButton circle><i i-ep-upload /></ElButton>
                    <ElButton circle><i i-ep-download /></ElButton>
                </div>
                <div flex-1 overflow-hidden box-border>
                    <ElTable :data="tableData" w-full box-border :border="true" height="100%" row-key="id"
                        @selection-change="handleSelectionChange">
                        <el-table-column fixed prop="locale" label="菜单名称" width="150">
                            <template #default="scope">
                                {{ t(scope.row.locale) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="类型" width="70">
                            <template #default="scope">
                                <el-tag>
                                    {{ dictStore.getDictItemsLabel('menu_type',scope.row.type) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="路由名称" width="150" />
                        <el-table-column prop="authority" label="权限标识" />
                        <el-table-column label="图标" width="60" align="center">
                            <template #default="scope">
                                <Icon :icon="scope.row.icon" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="disabled" label="状态" width="70">
                            <template #default="scope">
                                <ElTag :type="scope.row.disabled ? 'danger' : 'success'">
                                    {{ scope.row.disabled ? '禁用' : '启用' }}
                                </ElTag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="routePath" label="路由路径" />
                        <el-table-column prop="componentPath" label="组件路径" />
                        <el-table-column prop="sort" label="排序" width="55" align="center" />
                        <el-table-column fixed="right" label="操作" width="120">
                            <template #default="scope">
                                <div flex flex-justify-around flex-items-center>
                                    <ElTooltip effect="dark" content="添加下级菜单">
                                        <ElIcon @click="addClick(scope.row)">
                                            <i i-ep-circle-plus />
                                        </ElIcon>
                                    </ElTooltip>
                                    <ElTooltip effect="dark" content="编辑">
                                        <ElIcon @click="editClick(scope.row)">
                                            <i i-ep-edit />
                                        </ElIcon>
                                    </ElTooltip>
                                    <ElTooltip content="删除">
                                        <div flex>
                                            <el-popconfirm title="Are you sure to delete this?"
                                                @confirm="deleteClick(scope.row.id)">
                                                <template #reference>
                                                    <ElIcon>
                                                        <i i-ep-delete />
                                                    </ElIcon>
                                                </template>
                                            </el-popconfirm>
                                        </div>
                                    </ElTooltip>
                                </div>
                            </template>
                        </el-table-column>
                    </ElTable>
                </div>
            </div>
        </div>

        <!-- 新增/修改抽屉组件 -->
        <el-drawer v-model="drawer.visible"
            :title="drawer.mode == 'add' ? '新增菜单' : (drawer.mode == 'update' ? '修改菜单' : '')" direction="rtl"
            :before-close="handleClose">
            <el-form :model="menu" label-width="auto" ref="drawerFormRef">
                <el-form-item prop="name">
                    <el-radio-group v-model="menu.type">
                        <el-radio-button label="目录" value="0" />
                        <el-radio-button label="菜单" value="1" />
                        <el-radio-button label="按钮" value="2" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="标题" prop="name">
                    <el-input v-model="menu.name" />
                </el-form-item>
                <el-form-item label="上级菜单" prop="parentId">
                    <el-tree-select v-model="menu.parentId" :data="menusTree" check-strictly
                        :props="{ value: 'id', label: 'name', children: 'children' }" placeholder="请选择上级菜单" clearable />
                </el-form-item>
                <el-form-item label="权限标识" prop="permission">
                    <el-input v-model="menu.authority" />
                </el-form-item>
                <el-form-item label="图标" prop="icon" v-if="menu.type == '1'">
                    <IconSelector v-model="menu.icon" />
                </el-form-item>
                <el-form-item label="路由路径" prop="routePath" v-if="menu.type != '2'">
                    <el-input v-model="menu.routePath" />
                </el-form-item>
                <el-form-item label="组件路径" prop="componentPath" v-if="menu.type == '1'">
                    <el-input v-model="menu.componentPath" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="menu.sort" />
                </el-form-item>
                <div flex w-full flex-justify-between flex-items-center>
                    <el-form-item label="状态">
                        <el-switch v-model="menu.enabled" active-text="启用" inactive-text="禁用" inline-prompt
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                    </el-form-item>
                    <el-form-item label="是否缓存" v-if="menu.type == '1'">
                        <el-switch v-model="menu.cached"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                    </el-form-item>
                </div>
                <div flex w-full flex-justify-between flex-items-center>
                    <el-form-item label="是否外链" v-if="menu.type == '1'">
                        <el-switch v-model="menu.link"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                    </el-form-item>
                    <el-form-item label="是否隐藏" v-if="menu.type == '1'">
                        <el-switch v-model="menu.hidden"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                    </el-form-item>
                </div>
            </el-form>
            <template #footer>
                <ElDivider />
                <ElButton size="large" @click="submit">提交</ElButton>
            </template>
        </el-drawer>
    </div>
</template>

<style scoped lang="scss"></style>